Bubble Sort in Java

Course- Java >

We can create a java program to sort array elements using bubble sort. Bubble sort algorithm is known as the simplest sorting algorithm.

In bubble sort algorithm, array is traversed from first element to last element. Here, current element is compared with the next element. If current element is greater than the next element, it is swapped.

 
  1. public class BubbleSortExample {  
  2.     static void bubbleSort(int[] arr) {  
  3.         int n = arr.length;  
  4.         int temp = 0;  
  5.          for(int i=0; i < n; i++){  
  6.                  for(int j=1; j < (n-i); j++){  
  7.                           if(arr[j-1] > arr[j]){  
  8.                                  //swap elements  
  9.                                  temp = arr[j-1];  
  10.                                  arr[j-1] = arr[j];  
  11.                                  arr[j] = temp;  
  12.                          }  
  13.                           
  14.                  }  
  15.          }  
  16.   
  17.     }  
  18.     public static void main(String[] args) {  
  19.                 int arr[] ={3,60,35,2,45,320,5};  
  20.                  
  21.                 System.out.println("Array Before Bubble Sort");  
  22.                 for(int i=0; i < arr.length; i++){  
  23.                         System.out.print(arr[i] + " ");  
  24.                 }  
  25.                 System.out.println();  
  26.                   
  27.                 bubbleSort(arr);//sorting array elements using bubble sort  
  28.                  
  29.                 System.out.println("Array After Bubble Sort");  
  30.                 for(int i=0; i < arr.length; i++){  
  31.                         System.out.print(arr[i] + " ");  
  32.                 }  
  33.    
  34.         }  
  35. }  

Output:

Array Before Bubble Sort
3 60 35 2 45 320 5 
Array After Bubble Sort
2 3 5 35 45 60 320